package com.yuba.web.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuba.common.core.constant.Constants;
import com.yuba.common.core.domain.model.RegisterBody;
import com.yuba.common.core.enums.UserType;
import com.yuba.common.core.exception.user.UserException;
import com.yuba.common.core.utils.MessageUtils;
import com.yuba.common.tenant.helper.TenantHelper;
import com.yuba.common.web.config.properties.CaptchaProperties;
import com.yuba.system.domain.SysUser;
import com.yuba.system.domain.bo.SysUserBo;
import com.yuba.system.mapper.SysUserMapper;
import com.yuba.system.service.ISysUserService;
import com.yuba.web.service.IRegisterStrategy;
import com.yuba.web.service.SysRegisterService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 系统用户注册策略
 *
 * @author modakai
 */
@Slf4j
@Service("sys_user" + IRegisterStrategy.BASE_NAME)
@RequiredArgsConstructor
public class SysUserRegisterStrategy implements IRegisterStrategy {

    private final ISysUserService userService;
    private final SysUserMapper userMapper;
    private final CaptchaProperties captchaProperties;
    private final SysRegisterService registerService;


    @Override
    public void register(RegisterBody body) {
        String tenantId = body.getTenantId();
        String username = body.getUsername();
        String password = body.getPassword();
        // 校验用户类型是否存在
        String userType = UserType.getUserType(body.getUserType()).getUserType();

        boolean captchaEnabled = captchaProperties.getEnable();
        // 验证码开关
        if (captchaEnabled) {
            registerService.validateCaptcha(tenantId, username, body.getCode(), body.getUuid());
        }
        SysUserBo sysUser = new SysUserBo();
        sysUser.setUserName(username);
        sysUser.setNickName(username);
        sysUser.setPassword(BCrypt.hashpw(password));
        sysUser.setUserType(userType);

        boolean exist = TenantHelper.dynamic(tenantId, () -> {
            return userMapper.exists(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserName, sysUser.getUserName()));
        });
        if (exist) {
            throw new UserException("user.register.save.error", username);
        }
        boolean regFlag = userService.registerUser(sysUser, tenantId);
        if (!regFlag) {
            throw new UserException("user.register.error");
        }
        registerService.recordLoginInfo(tenantId, username, Constants.REGISTER, MessageUtils.message("user.register.success"));
    }


}
